﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProjectEulerSolutions.Problems
{
    /*
     * Let (a, b, c) represent the three sides of a right angle triangle with integral length sides. It is possible to place four such triangles together to form a square with length c.

For example, (3, 4, 5) triangles can be placed together to form a 5 by 5 square with a 1 by 1 hole in the middle and it can be seen that the 5 by 5 square can be tiled with twenty-five 1 by 1 squares.

However, if (5, 12, 13) triangles were used then the hole would measure 7 by 7 and these could not be used to tile the 13 by 13 square.

Given that the perimeter of the right triangle is less than one-hundred million, how many Pythagorean triangles would allow such a tiling to take place?

     * */
    class Problem139 : IProblem
    {
        public string Calculate()
        {
            long limit = 100000000;
            long count = 0;
            long m = 2;
            while (2 * m * (m + 1) < limit)
            {
                long n = m % 2 + 1;
                long p = 2 * m * (m + n);
                while (p < limit && n < m)
                {
                    p = 2 * m * (m + n);
                    if (CommonFunctions.GreatestCommonDivisor(m, n) == 1)
                    {
                        long c = m * m + n * n;
                        long a = 2 * m * n;
                        long b = m * m - n * n;

                        long diff = a - b;
                        if (diff < 0)
                            diff *= -1;

                        if (c % diff == 0)
                        {
                            Console.WriteLine("{0} {1} {2}, m={3}, n={4}", a, b, c, m, n);
                            count += limit / p;

                            m = (long)(m * 2.3); //magic
                            n = m % 2;
                        }
                    }


                    n += 2;
                }
                m++;
            }

            return count.ToString();
        }
    }
}
